1

Create a matrix with 8 rows and 8 columns filled with random numbers in a range between 1 and 1000.
You can use the sample() function to create the numbers.
library(dplyr)

fancy_matrix <-
  sample(1:1000, 8*8, replace = TRUE) |> 
  matrix(nrow = 8, ncol = 8)

fancy_matrix
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,]  733  117  362  514  463  414  149  518
## [2,]  912  175  560  686  250  580  824   79
## [3,]  983  693  976  835   72  647  973  309
## [4,]  542  613  712  854  761  638  522  870
## [5,]  408  361  815   75  288  619   85  751
## [6,]   64  641  962  619  425  518  138  546
## [7,]  851  497  640  201  550  970  885  733
## [8,]  947  764  484  403  241  551  385  119

2

Now use this matrix to create a raster layer and plot it.
The terra::rast() function can be fed with matrices to create a raster layer.
library(terra)

fancy_raster_layer <- terra::rast(fancy_matrix)

terra::plot(fancy_raster_layer)

The terra::rast() function can not only be used to create raster data on the fly, which is also quite boring. Instead, we can use it to import already prepared data.

3

Import one of the raster .tiff files in the ./data folder of the workshop directory.
Make sure your file paths are set correctly. You can check them with getwd(). Setting is done with setwd().
immigrants_cologne <- terra::rast("./data/immigrants_cologne.tif")

4

Import the data on immigrants and inhabitants. Create a new layer showing the proportion of immigrants in each grid cell between 0 and 1. Next, apply z-standardization and dichotomize the data to get information about which grid cells deviate from the overall mean. Plot both “versions” of the data to see how they compare.
You can handle raster layers as any simple data table using +, -, or / operators. Z-standardization can be applied using the terra::scale() function.
# load all layers
immigrants_cologne <-
  terra::rast("./data/immigrants_cologne.tif")

inhabitants_cologne <-
  terra::rast("./data/inhabitants_cologne.tif")

# create proportation layer
immigrants_proportion <- immigrants_cologne / inhabitants_cologne

# scale data
immigrants_proportion_scaled <- terra::scale(immigrants_proportation)

immigrants_proportion_scaled[immigrants_proportion_scaled < 0] <- 0
immigrants_proportion_scaled[immigrants_proportion_scaled > 0] <- 1

library(tmap)

tm_shape(immigrants_proportion) +
  tm_raster(palette = "-viridis")

tm_shape(immigrants_proportion_scaled) +
  tm_raster(palette = "-viridis")